package com.luoqiz.caffeine.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.luoqiz.caffeine.entity.Member;
import com.luoqiz.common.httpEntity.PageResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * @Cacheable 触发缓存入口（这里一般放在创建和获取的方法上）
 * @CacheEvict 触发缓存的eviction（用于删除的方法上）
 * @CachePut 更新缓存且不影响方法执行（用于修改的方法上，该注解下的方法始终会被执行）
 * @Caching 将多个缓存组合在一个方法上（该注解可以允许一个方法同时设置多个注解）
 * @CacheConfig 在类级别设置一些缓存相关的共同配置（与其它缓存配合使用）
 */

@Slf4j
@RestController
@RequestMapping("cache")
public class CacheController {

	@PostMapping("getMemberDomain")
	@Cacheable(value = "listMember", key = "#member.id", sync = true)
	public Member getMemberDomain(@RequestBody Member member) {
		log.info("进行对象的缓存操作");
		return member;
	}

	@GetMapping("getMember")
	@Cacheable(value = "listMember", key = "#username", sync = true)
	public Member getMember(String username) {
		log.info("进行缓存操作");
		Member member = new Member(1, username, new Date(), UUID.randomUUID().toString(), false);
		return member;
	}

	@GetMapping("putMember")
	@CachePut(value = "listMember", key = "#username")
	public Member putMember(String username) {
		log.info("进行更新操作");
		Member member = new Member(1, username, new Date(), UUID.randomUUID().toString(), true);
		return member;
	}

	@GetMapping("delMember")
	@CacheEvict(value = "listMember", key = "#username")
	public Boolean delMember(String username) {
		log.info("进行删除操作");
		return true;
	}

	@GetMapping("dict")
	@Cacheable(value = "dictCatalogItem", key = "#username", sync = true)
	public String getdict(String username) {
		log.info("进行字典缓存操作 ----{}", username);
		return username;
	}

	// 泛型测试
	@GetMapping("listMember")
	public PageResponse<Integer, List<Member>> listMember(int length) {
		log.info("进行泛型返回值测试");
		ArrayList<Member> memberList = new ArrayList<>();
		for (int i = 0; i < length; i++) {
			memberList.add(
					new Member(i, "username--" + i, new Date(), UUID.randomUUID().toString(), Math.random() > 0.5));
		}
		return new PageResponse<Integer, List<Member>>(memberList.size(), memberList);
	}
}
